package com.qili.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.entity.base.BaseDict;
import com.qili.entity.base.Col;
import com.qili.entity.base.FormType;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.SupervisorFileTemp;
import com.qili.entity.supervisor.SupervisorProjectFormsData;
import com.qili.entity.supervisor.dto.SupervisorProjectFromsDTO;
import com.qili.mapper.search.ItFormMapper;
import com.qili.service.it.FormBaseService;
import com.qili.service.it.impl.*;
import com.qili.service.search.ItFormAboutService;
import com.qili.service.supervisor.SupervisorFileTempService;
import com.qili.util.*;
import com.qili.util.DateUtil;
import lombok.extern.java.Log;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @author liuyang
 * @date 2021/5/10
 * @description IT Form表单相关
 * 包括   科研项目信息  知识产权信息  标准规范信息
 */
@Log
@Controller
@RequestMapping("/search/decision")
public class ItFormAboutController {

    @Autowired
    ItFormAboutService itFormAboutService;
    @Autowired
    UploadUtil uploadUtil;
    @Autowired
    SupervisorFileTempService tempService;
    @Autowired
    ZhengzhongBZFormServiceImpl zhengzhongBZFormService;
    @Autowired
    KeYanXiangMuFormServiceImpl keYanXiangMuFormService;
    @Autowired
    LunWenFormServiceImpl lunWenFormService;
    @Autowired
    ZhuanliFormServiceImpl zhuanliFormService;
    @Autowired
    RuanZhuFormServiceImpl ruanZhuFormService;
    @Autowired
    ShuZhuFormServiceImpl shuZhuFormService;
    @Autowired
    JiChengDianLuFormServiceImpl jiChengDianLuFormService;
    @Autowired
    @Qualifier("FormBaseService")
    FormBaseService formBaseService;
    @Autowired
    ItFormMapper itFormMapper;

    /**
     * 显示表单类台账页面
     * [科研项目台账,论文台账,专利台账,软著台账,集成电路布图台账,书著台账,标准台账]
     * @param model
     * @return
     */
    @GetMapping("/itForm/book/{formTypeCode}")
    @RequiresPermissions (value={"zn:jc:kyxm:tz","zn:jc:lw:tz","zn:jc:zl:tz","zn:jc:rz:tz","zn:jc:jcdl:tz","zn:jc:sz:tz","zn:jc:bz:tz"}, logical= Logical.OR)
    public String showItFormTzPage(@PathVariable String formTypeCode,Model model) {
        if(StringUtils.isBlank(formTypeCode)){
            throw new RuntimeException("显示表单台账页面时,表单类型编码为空");
        }
        String returnPage = "";
        FormType formType = FormType.getFormType(formTypeCode);
        switch (formType){
            case ZZCBBZ:
                //状态:
                model.addAttribute("bzztList",DictUtil.getDictByType(DictTypes.STATE));
                model.addAttribute("bzztListStr",JSON.toJSONString(DictUtil.getDictByType(DictTypes.STATE)));
                //标准级别
                model.addAttribute("bzjbList",DictUtil.getDictByType(DictTypes.BZJB));
                model.addAttribute("bzjbListStr",JSON.toJSONString(DictUtil.getDictByType(DictTypes.BZJB)));
                //正中角色
                model.addAttribute("zzjsList",DictUtil.getDictByType(DictTypes.ZZJS));
                model.addAttribute("zzjsListStr",JSON.toJSONString(DictUtil.getDictByType(DictTypes.ZZJS)));
                returnPage = "/decision/itform/zzcbbztz";
                break;
            case ZL:
                //专利类型:
                model.addAttribute("zllxList",DictUtil.getDictByType(DictTypes.ZLLX));
                model.addAttribute("zllxListStr",JSON.toJSONString(DictUtil.getDictByType(DictTypes.ZLLX)));
                //阶段:
                model.addAttribute("jdList",DictUtil.getDictByType(DictTypes.ITJD));
                model.addAttribute("jdListStr",JSON.toJSONString(DictUtil.getDictByType(DictTypes.ITJD)));
                returnPage = "/decision/itform/zltz";
                break;
            case RZ:
                returnPage = "/decision/itform/rztz";
                break;
            case JCDLBT:
                returnPage = "/decision/itform/jcdlbttz";
                break;
            case LW:
                //获取期刊类型
                model.addAttribute("qklxList",DictUtil.getDictByType(DictTypes.QKLX));
                model.addAttribute("qklxListStr", JSON.toJSONString(DictUtil.getDictByType(DictTypes.QKLX)));
                //获取所属期刊分类
                model.addAttribute("qkflList",DictUtil.getDictByType(DictTypes.QKFL));
                model.addAttribute("qkflListStr", JSON.toJSONString(DictUtil.getDictByType(DictTypes.QKFL)));
//                //获取所有论文中,作者最多的作者数量:
//                List<String> AuthorIndexList = lunWenFormService.getAuthorIndexListTz(new SupervisorProjectFromsDTO());
//                model.addAttribute("AuthorIndexList",AuthorIndexList);
//                model.addAttribute("AuthorIndexListStr",JSON.toJSONString(AuthorIndexList));
                returnPage = "/decision/itform/lwtz";
                break;
            case SZ:
                returnPage = "/decision/itform/sztz";
                break;
            case KYXMK:
                //获取计划类型
                model.addAttribute("jhlbList",DictUtil.getDictByType(DictTypes.JHLB));
                model.addAttribute("jhlbListStr", JSON.toJSONString(DictUtil.getDictByType(DictTypes.JHLB)));
                //获取项目级别
                model.addAttribute("xmjbList",DictUtil.getDictByType(DictTypes.XMJB));
                model.addAttribute("xmjbListStr",JSON.toJSONString(DictUtil.getDictByType(DictTypes.XMJB)));
                //项目进度
                model.addAttribute("xmjdList",DictUtil.getDictByType(DictTypes.XMJD));
                model.addAttribute("xmjdListStr",JSON.toJSONString(DictUtil.getDictByType(DictTypes.XMJD)));
                returnPage = "/decision/itform/kyxmtz";
        }
        return returnPage;
    }

    /**
     * 显示表单类统计页面
     * [科研项目统计,论文统计,专利统计,软著统计,集成电路布图统计,书著统计,标准统计]
     * @param model
     * @return
     */
    @GetMapping("/itForm/statistics/{formTypeCode}")
    @RequiresPermissions (value={"zn:jc:kyxm:tj","zn:jc:lw:tj","zn:jc:zl:tj","zn:jc:rz:tj","zn:jc:jcdl:tj","zn:jc:sz:tj","zn:jc:bz:tj"}, logical= Logical.OR)
    public String showItFormTjPage(@PathVariable String formTypeCode,Model model){
        if(StringUtils.isBlank(formTypeCode)){
            throw new RuntimeException("显示表单统计页面时,表单类型编码为空");
        }
        String returnPage = "";
        FormType formType = FormType.getFormType(formTypeCode);
        switch (formType){
            case ZZCBBZ:
                //正中角色
                model.addAttribute("zzjsList",DictUtil.getDictByType(DictTypes.ZZJS));
                returnPage = "/decision/itform/zzcbbztj";
                break;
            case ZL:
                returnPage = "/decision/itform/zltj";
                break;
            case RZ:
                returnPage = "/decision/itform/rztj";
                break;
            case JCDLBT:
                returnPage = "/decision/itform/jcdlbttj";
                break;
            case LW:
                //获取期刊类型
                model.addAttribute("qklxList",DictUtil.getDictByType(DictTypes.QKLX));
                model.addAttribute("qklxListStr", JSON.toJSONString(DictUtil.getDictByType(DictTypes.QKLX)));
                //获取所属期刊分类
                model.addAttribute("qkflList",DictUtil.getDictByType(DictTypes.QKFL));
                model.addAttribute("qkflListStr", JSON.toJSONString(DictUtil.getDictByType(DictTypes.QKFL)));
                returnPage = "/decision/itform/lwtj";
                break;
            case SZ:
                returnPage = "/decision/itform/sztj";
                break;
            case KYXMK:
                //获取计划类型
                model.addAttribute("jhlbList",DictUtil.getDictByType(DictTypes.JHLB));
                model.addAttribute("jhlbListStr", JSON.toJSONString(DictUtil.getDictByType(DictTypes.JHLB)));
                //获取项目级别
                model.addAttribute("xmjbList",DictUtil.getDictByType(DictTypes.XMJB));
                model.addAttribute("xmjbListStr",JSON.toJSONString(DictUtil.getDictByType(DictTypes.XMJB)));
                //项目进度
                model.addAttribute("xmjdList",DictUtil.getDictByType(DictTypes.XMJD));
                model.addAttribute("xmjdListStr",JSON.toJSONString(DictUtil.getDictByType(DictTypes.XMJD)));
                //查询所有的项目负责人:
                List<String> xmfzrList = keYanXiangMuFormService.getXmfzrList();
                model.addAttribute("xmfzrList",xmfzrList);
                returnPage = "/decision/itform/kyxmtj";
        }
        return returnPage;
    }

    /**
     * 显示成员列表页面(科研项目统计页面点击团队)
     * @return
     */
    @GetMapping("/showMembers")
    public String showMembersPage(){
        return "/decision/itform/members";
    }

    @ResponseBody
    @GetMapping("/getAuthorCount")
    public JsonUtil getAuthorCount(SupervisorProjectFromsDTO formInfo){
        List<String> authorIndexList = lunWenFormService.getAuthorIndexListTz(formInfo);
        JsonUtil result = new JsonUtil();
        result.setFlag(true);
        result.setData(authorIndexList);
        return result;
    }

    @ResponseBody
    @GetMapping("/getZhuBianAndBianWeiCount")
    public JsonUtil getZhuBianAndBianWeiList(SupervisorProjectFromsDTO formInfo){
        //首先根据条件获取符合条件的表单id:
        List<String> spfIdList = shuZhuFormService.getSpfIdList(formInfo);
        if(CollectionUtil.isNotEmpty(spfIdList)){
            formInfo.setObj8(spfIdList);
        }
        //获取副主编最大数量:
        formInfo.setExcelStr1("zhubian");
        Integer fuZhuBianCount = shuZhuFormService.getMaxCount(formInfo);
        if(fuZhuBianCount == null){
            fuZhuBianCount = 0;
        }
        //获取编委最大数量:
        formInfo.setExcelStr1("bianwei");
        Integer bianWeiCount = shuZhuFormService.getMaxCount(formInfo);
        if(bianWeiCount == null){
            bianWeiCount = 0;
        }
        JsonUtil result = new JsonUtil();
        result.setFlag(true);
        Map paraMap = new HashMap();
        paraMap.put("fuZhuBianCount",fuZhuBianCount == null ? 0:fuZhuBianCount);
        paraMap.put("bianWeiCount",bianWeiCount == null ? 0:bianWeiCount);
        result.setData(paraMap);
        return result;
    }

    /**
     * 获取符合条件的正中起草人的最大个数
     * @param formInfo
     * @return
     */
    @ResponseBody
    @GetMapping("/getQiCaoRenCount")
    public JsonUtil getQiCaoRenCount(SupervisorProjectFromsDTO formInfo){
        JsonUtil result = new JsonUtil();
        if(StringUtils.isNotBlank(formInfo.getSpfF1())){
            formInfo.setSpfF1("%"+formInfo.getSpfF1()+"%");
        }
        //先根据条件查询符合条件的form表的spf_id
        List<String> spfIdList = zhengzhongBZFormService.getSpfIdList(formInfo);
        Integer count = 0;
        Map paraMap = new HashMap();
        if(CollectionUtil.isNotEmpty(spfIdList)){
            paraMap.put("spfIdList",spfIdList);
            count = zhengzhongBZFormService.getQiCaoRenCount(paraMap);
        }
        result.setFlag(true);
        result.setData(count == null ? 0 : count);
        return result;
    }


    /**
     * 获取表单相关台账表格数据
     * @return
     */
    @ResponseBody
    @RequestMapping("/form/book/{formTypeCode}")
    public ReType selectFormBook(@PathVariable String formTypeCode, SupervisorProjectFromsDTO formInfo, String page, String limit){
        ReType reType = new ReType();
        if(StringUtils.isBlank(formTypeCode)){
            log.warning("查询表单类台账时,没有获取到表单类型编码");
            return null;
        }
        formInfo.setSpfF30(formTypeCode);
        FormType formType = FormType.getFormType(formTypeCode);
        switch (formType){
            case ZZCBBZ:
                return zhengzhongBZFormService.selectFormBook(formInfo,page,limit);
            case ZL:
                return zhuanliFormService.selectFormBook(formInfo,page,limit);
            case RZ:
                return ruanZhuFormService.selectFormBook(formInfo,page,limit);
            case JCDLBT:
                return jiChengDianLuFormService.selectFormBook(formInfo,page,limit);
            case LW:
                return lunWenFormService.selectFormBook(formInfo,page,limit);
            case SZ:
                return shuZhuFormService.selectFormBook(formInfo,page,limit);
            case KYXMK:
                return keYanXiangMuFormService.selectFormBook(formInfo,page,limit);
        }
        return null;
    }

    /**
     * 获取表单统计的表头
     * 一些需要动态显示表头的使用此方法
     * @param formTypeCode
     * @param formInfo
     * @param index
     * @return
     */
    @ResponseBody
    @RequestMapping("/form/statistics/tableHead/{formTypeCode}")
    public JsonUtil getFormStatisticstableHead(@PathVariable String formTypeCode, SupervisorProjectFromsDTO formInfo,String index){
        JsonUtil result = new JsonUtil();
        if(StringUtils.isBlank(formTypeCode)){
            log.warning("查询表单类统计表格表头时,没有获取到表单类型编码");
            return null;
        }
        formInfo.setSpfF30(formTypeCode);
        List<Col> colList = formBaseService.getFormStatisticstableHead(formTypeCode,formInfo,index);
        result.setFlag(true);
        result.setData(colList);
        return result;
    }

    @ResponseBody
    @RequestMapping("/form/statistics/detail/{formTypeCode}")
    public ReType getFormStatisticsDetail(@PathVariable String formTypeCode,SupervisorProjectFromsDTO formInfo,String index,String page,String limit){
        if(StringUtils.isBlank(formTypeCode)){
            log.warning("显示数量详情页时,没有获取到表单类型编码");
            return null;
        }
        formInfo.setSpfF30(formTypeCode);
        FormType formType = FormType.getFormType(formTypeCode);
        switch (formType){
            case LW:
                switch (index){
                    case "0":
                        return lunWenFormService.getFormStatisticsDetail(formInfo,index,page,limit);
                }
                break;
        }
        return null;
    }

    /**
     * 显示表单统计数字详情页
     * @param formTypeCode
     * @param formInfo
     * @param index
     * @return
     */
    @RequestMapping("/form/statistics/showCountDetailPage/{formTypeCode}")
    public String showCountDetailPage(@PathVariable String formTypeCode, SupervisorProjectFromsDTO formInfo,String index,Model model){
        if(StringUtils.isBlank(formTypeCode)){
            log.warning("显示数量详情页时,没有获取到表单类型编码");
            return null;
        }
        FormType formType = FormType.getFormType(formTypeCode);
        switch (formType){
            case LW:
                switch (index){
                    case "0":
                        return "/decision/itform/members";
                }
                break;
            case KYXMK:
                //获取计划类型
                model.addAttribute("jhlbList",DictUtil.getDictByType(DictTypes.JHLB));
                model.addAttribute("jhlbListStr", JSON.toJSONString(DictUtil.getDictByType(DictTypes.JHLB)));
                //获取项目级别
                model.addAttribute("xmjbList",DictUtil.getDictByType(DictTypes.XMJB));
                model.addAttribute("xmjbListStr",JSON.toJSONString(DictUtil.getDictByType(DictTypes.XMJB)));
                //项目进度
                model.addAttribute("xmjdList",DictUtil.getDictByType(DictTypes.XMJD));
                model.addAttribute("xmjdListStr",JSON.toJSONString(DictUtil.getDictByType(DictTypes.XMJD)));
                switch (index){
                    case "0":
                        return "/decision/itform/kyxmCountDetail";
                    case "1":
                        return "/decision/itform/kyxmCountDetail";
                }
            case ZL:
                //专利类型:
                model.addAttribute("zllxList",DictUtil.getDictByType(DictTypes.ZLLX));
                model.addAttribute("zllxListStr",JSON.toJSONString(DictUtil.getDictByType(DictTypes.ZLLX)));
                //阶段:
                model.addAttribute("jdList",DictUtil.getDictByType(DictTypes.ITJD));
                model.addAttribute("jdListStr",JSON.toJSONString(DictUtil.getDictByType(DictTypes.ITJD)));
                switch (index){
                    case "0":
                        return "/decision/itform/zlCountDetail";
                }
            case SZ:
                //书著
                switch (index){
                    case "0":
                        return "/decision/itform/szCountDetail";
                }
        }
        return null;
    }

    /**
     * 获取表单相关统计表格数据
     * @return
     */
    @ResponseBody
    @RequestMapping("/form/statistics/{formTypeCode}")
    public ReType selectFormScientific(@PathVariable String formTypeCode, SupervisorProjectFromsDTO formInfo, String page, String limit,String index){
        ReType reType = new ReType();
        if(StringUtils.isBlank(formTypeCode)){
            log.warning("查询表单类统计表格数据时,没有获取到表单类型编码");
            return null;
        }
        formInfo.setSpfF30(formTypeCode);
        return formBaseService.selectFormStatisticsTableData(formTypeCode,formInfo,index,page,limit);
    }

    /**
     * 预览台账表格
     * @return
     */
    @ResponseBody
    @RequestMapping("/form/book/viewTable/{formTypeCode}")
    public JsonUtil viewBookTable(@PathVariable String formTypeCode, SupervisorProjectFromsDTO formInfo){
        JsonUtil result = new JsonUtil();
        if(StringUtils.isBlank(formTypeCode)){
            log.warning("预览表单类台账表格时,没有获取到表单类型编码");
            return null;
        }
        ReType reType1 = selectFormBook(formTypeCode, formInfo, "1", Integer.MAX_VALUE + "");
        List<?> data1 = reType1.getData();
        if(CollectionUtil.isNotEmpty(data1)){
            try{
//            List<SupervisorProjectFromsDTO> data = (List<SupervisorProjectFromsDTO>)reType1.getData();
            List<?> data = handlerData(formTypeCode,reType1.getData());
            HashMap dataMap = new HashMap();
            dataMap.put("records",data);
            dataMap.put("yearmonth",DateUtil.getCurrentDateNoSpliter());
            if("110005".equals(formTypeCode)){
                //获取所有的作者:
                List<String> authorIndexList = lunWenFormService.getAuthorIndexListTz(formInfo);
                dataMap.put("authorIndex", authorIndexList);
            }else if("110006".equals(formTypeCode)){
                //书著台账,获取副主编和编委的最大值:
                ArrayList<Map> zhuBianList = new ArrayList<>();
                formInfo.setExcelStr1("zhubian");
                Integer zhuBianMaxCount = shuZhuFormService.getMaxCount(formInfo);
                if(zhuBianMaxCount != null && zhuBianMaxCount>0){
                    for(int i=0;i<zhuBianMaxCount;i++){
                        Map<String,String> aZhuBianMap = new HashMap();
                        aZhuBianMap.put("name",i == 0 ? "副主编" : "副主编"+(i+1));
                        aZhuBianMap.put("index","zhuBian"+i);
                        zhuBianList.add(aZhuBianMap);
                    }
                }
                ArrayList<Map> bianWeiList = new ArrayList<>();
                formInfo.setExcelStr1("bianwei");
                Integer bianWeiMaxCount = shuZhuFormService.getMaxCount(formInfo);
                if(bianWeiMaxCount != null && bianWeiMaxCount>0){
                    for(int i=0;i<bianWeiMaxCount;i++){
                        Map<String,String> aBianWeiMap = new HashMap();
                        aBianWeiMap.put("name",i == 0 ? "编委" : "编委"+(i+1));
                        aBianWeiMap.put("index","bianWei"+i);
                        bianWeiList.add(aBianWeiMap);
                    }
                }
                dataMap.put("zhuBianList",zhuBianList);
                dataMap.put("bianWeiList",bianWeiList);
            }else if("110001".equals(formTypeCode)){
                //先根据条件查询符合条件的form表的spf_id
                List<String> spfIdList = zhengzhongBZFormService.getSpfIdList(formInfo);
                Integer count = 0;
                Map paraMap = new HashMap();
                if(CollectionUtil.isNotEmpty(spfIdList)){
                    paraMap.put("spfIdList",spfIdList);
                    count = zhengzhongBZFormService.getQiCaoRenCount(paraMap);
                }
                ArrayList<Map> qiCaoRenList = new ArrayList<>();
                if(count > 0){
                    for(int i=0;i<count;i++){
                        Map<String,String> aQiCaoRenMap = new HashMap();
                        aQiCaoRenMap.put("name","起草人姓名" +(i+1));
                        aQiCaoRenMap.put("nameField","qiCaoRenName"+i);
                        aQiCaoRenMap.put("index","qiCaoRenOrder"+i);
                        qiCaoRenList.add(aQiCaoRenMap);
                    }
                }
                dataMap.put("qiCaoRenList",qiCaoRenList);
            }
            String fileName  = getExportExcelName(formTypeCode);
            File formExcel = createFormExcel(formTypeCode, fileName, dataMap);
            String tempFilePath = uploadUtil.getTempPath()+File.separator+ new Date().getTime()
                    +File.separator+fileName+formExcel.getName().substring(formExcel.getName().lastIndexOf("."));
            File tempFile = new File(tempFilePath);

            if(!tempFile.getParentFile().exists()){
                tempFile.getParentFile().mkdirs();
            }
            tempFile.createNewFile();
            FileUtils.copyFile(formExcel,tempFile);
            formExcel.delete();
            SupervisorFileTemp temp = new SupervisorFileTemp();
            temp.setUrl(tempFile.getPath());
            temp.setFileName(tempFile.getName());
            temp.setFileType(tempFile.getName().substring(tempFile.getName().lastIndexOf(".")));
            temp.setType(formTypeCode+"tz");
            tempService.insertSelective(temp);
            result.setFlag(true);
            result.setData(temp.getId());
            return result;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

            }
        }
        result.setFlag(false);
        return result;
    }

    /**
     * 导出表单相关台账表格数据
     * @return
     */
    @RequestMapping("/form/export/book/{formTypeCode}")
    public void exportExcel(@PathVariable String formTypeCode, SupervisorProjectFromsDTO formInfo, HttpServletRequest request, HttpServletResponse response){
        ReType reType = new ReType();
        if(StringUtils.isBlank(formTypeCode)){
            log.warning("导出表单类台账时,没有获取到表单类型编码");
            return ;
        }
        ReType reType1 = selectFormBook(formTypeCode, formInfo, "1", Integer.MAX_VALUE + "");
        List<?> data1 = reType1.getData();
        if(CollectionUtil.isNotEmpty(data1)){
//            List<SupervisorProjectFromsDTO> data = (List<SupervisorProjectFromsDTO>)reType1.getData();
            List<?> data = handlerData(formTypeCode,data1);
            HashMap dataMap = new HashMap();
            dataMap.put("records",data);
            dataMap.put("yearmonth",DateUtil.getCurrentDateNoSpliter());
            if("110005".equals(formTypeCode)){
                //获取所有的作者:
                List<String> authorIndexList = lunWenFormService.getAuthorIndexListTz(formInfo);
                dataMap.put("authorIndex", authorIndexList);
            }else if("110006".equals(formTypeCode)){
                //书著台账,获取副主编和编委的最大值:
                ArrayList<Map> zhuBianList = new ArrayList<>();
                formInfo.setExcelStr1("zhubian");
                Integer zhuBianMaxCount = shuZhuFormService.getMaxCount(formInfo);
                if(zhuBianMaxCount != null && zhuBianMaxCount>0){
                    for(int i=0;i<zhuBianMaxCount;i++){
                        Map<String,String> aZhuBianMap = new HashMap();
                        aZhuBianMap.put("name",i == 0 ? "副主编" : "副主编"+(i+1));
                        aZhuBianMap.put("index","zhuBian"+i);
                        zhuBianList.add(aZhuBianMap);
                    }
                }
                ArrayList<Map> bianWeiList = new ArrayList<>();
                formInfo.setExcelStr1("bianwei");
                Integer bianWeiMaxCount = shuZhuFormService.getMaxCount(formInfo);
                if(bianWeiMaxCount != null && bianWeiMaxCount>0){
                    for(int i=0;i<bianWeiMaxCount;i++){
                        Map<String,String> aBianWeiMap = new HashMap();
                        aBianWeiMap.put("name",i == 0 ? "编委" : "编委"+(i+1));
                        aBianWeiMap.put("index","bianWei"+i);
                        bianWeiList.add(aBianWeiMap);
                    }
                }
                dataMap.put("zhuBianList",zhuBianList);
                dataMap.put("bianWeiList",bianWeiList);
            }else if("110001".equals(formTypeCode)){
                //先根据条件查询符合条件的form表的spf_id
                List<String> spfIdList = zhengzhongBZFormService.getSpfIdList(formInfo);
                Integer count = 0;
                Map paraMap = new HashMap();
                if(CollectionUtil.isNotEmpty(spfIdList)){
                    paraMap.put("spfIdList",spfIdList);
                    count = zhengzhongBZFormService.getQiCaoRenCount(paraMap);
                }
                ArrayList<Map> qiCaoRenList = new ArrayList<>();
                if(count > 0){
                    for(int i=0;i<count;i++){
                        Map<String,String> aQiCaoRenMap = new HashMap();
                        aQiCaoRenMap.put("name","起草人姓名" +(i+1));
                        aQiCaoRenMap.put("nameField","qiCaoRenName"+i);
                        aQiCaoRenMap.put("index","qiCaoRenOrder"+i);
                        qiCaoRenList.add(aQiCaoRenMap);
                    }
                }
                dataMap.put("qiCaoRenList",qiCaoRenList);
            }
            String fileName  = getExportExcelName(formTypeCode);
            try {
                ExcelExportUtil.exportExcel(response,dataMap,fileName,formTypeCode);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    private void addIndex(List<JSONObject> jsonObjects) {
        if(CollectionUtil.isNotEmpty(jsonObjects)){
            for(int i=0;i<jsonObjects.size();i++){
                JSONObject jsonObject = jsonObjects.get(i);
                jsonObject.put("fileInd",(i+1)+"");
            }
        }
    }

    private void mergeTable(File source,File target) {
        Workbook wb = null;
        OutputStream out = null;
        try {
            wb = WorkbookFactory.create(new File(source.getPath()));
            Sheet sheet = wb.getSheetAt(0);
            int firstRowNum = sheet.getFirstRowNum();
            int lastRowNum = sheet.getLastRowNum();
            for(int i=2;i<lastRowNum;i++){
                Row row = sheet.getRow(i);
                short lastCellNum = row.getLastCellNum();
                if(lastCellNum >= 5){
                    //获取项目负责人数
                    Cell countCell = row.getCell(2);
                    if(countCell != null){
                        countCell.setCellType(Cell.CELL_TYPE_NUMERIC);
                        double numericCellValue = countCell.getNumericCellValue();
                        int count = (int) numericCellValue;
                        if(count >1){
                            //超过一行，需要合并单元格
                            mergeRegion(sheet,i,i+count-1,0,0);
                            mergeRegion(sheet,i,i+count-1,1,1);
                            mergeRegion(sheet,i,i+count-1,2,2);
                            i += (count-1);
                        }
                    }
                }
            }
            out = new FileOutputStream(target.getPath());
            wb.write(out);
        }catch (InvalidFormatException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                if(out != null){
                    out.flush();
                    out.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 合并单元格
     * @param firstRow 开始行
     * @param lastRow  结束行
     * @param firstCol 开始列
     * @param lastCol  结束列
     */
    private void mergeRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
    }

    /**
     * 判断合并了行
     */
    private boolean isMergedRow(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row == firstRow && row == lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 预览统计表格
     * @return
     */
    @ResponseBody
    @RequestMapping("/form/statistics/viewTable/{formTypeCode}")
    public JsonUtil viewStatisticsTable(@PathVariable String formTypeCode, SupervisorProjectFromsDTO formInfo,String index){
        JsonUtil result = new JsonUtil();
        if(StringUtils.isBlank(formTypeCode)){
            log.warning("预览表单类统计表格时,没有获取到表单类型编码");
            return null;
        }
        formInfo.setSpfF30(formTypeCode);
        ReType reType1 = selectFormScientific(formTypeCode, formInfo, "1", Integer.MAX_VALUE + "",index);
        List<?> data1 = reType1.getData();
        if(CollectionUtil.isNotEmpty(data1)){
            try{
                List<Map> data = (List<Map>)reType1.getData();
                for (int i = 0; i <data.size() ; i++) {
                    Map map = data.get(i);
                    map.put("fileInd",i+1);
                }
                String s = JSONArray.toJSONString(data);
                List<JSONObject> jsonObjects = JSONArray.parseArray(s, JSONObject.class);
                HashMap dataMap = new HashMap();
                if("110007".equals(formTypeCode)){
                    if("0".equals(index) || "1".equals(index)){
                        List<String> kyxmYears0 = itFormMapper.getKyxmYears0(formInfo);
                        dataMap.put("years",kyxmYears0);
                    }
                    if("3".equals(index)){
                        //项目级别列表
                        List<BaseDict> xmjbDictList = DictUtil.getDictByType(DictTypes.XMJB);
                        dataMap.put("xmjbDictList",xmjbDictList);
                        addIndex(jsonObjects);
                    }
                }else if("110005".equals(formTypeCode)){
                    List<String> authorIndexListTj = lunWenFormService.getAuthorIndexListTj(formInfo);
                    if(CollectionUtil.isNotEmpty(authorIndexListTj)){
                        List<String> newResult = new ArrayList<String>();
                        for(int i=0;i<authorIndexListTj.size();i++){
                            newResult.add(authorIndexListTj.get(i));
                            if(i > 4){
                                break;
                            }
                        }
                        dataMap.put("authorIndexList",newResult);
                    }
                    List<BaseDict> dictByType = DictUtil.getDictByType(DictTypes.QKLX);
                    dataMap.put("qklxList",dictByType);
                    addIndex(jsonObjects);
                }else if("110002".equals(formTypeCode)){
                    //填充专利类型:
                    List<BaseDict> zllxList = DictUtil.getDictByType(DictTypes.ZLLX);
                    dataMap.put("zllxList",zllxList);
                    addIndex(jsonObjects);
                    if("0".equals(index)){
                        List<String> famingrenIndexListTj = zhuanliFormService.getFamingrenIndexListTj(formInfo);
                        if(CollectionUtil.isNotEmpty(famingrenIndexListTj)){
                            List<String> tableFaMingRenIndexList = new ArrayList<>();
                            for(int i=0;i<famingrenIndexListTj.size();i++){
                                tableFaMingRenIndexList.add(famingrenIndexListTj.get(i));
                                if(i > 6){
                                    break;
                                }
                            }
                            dataMap.put("famingrenIndexList",tableFaMingRenIndexList);
                        }
                    }
                }else if("110003".equals(formTypeCode)){
                    addIndex(jsonObjects);
                }else if("110006".equals(formTypeCode)){
                    //书著统计:
                    addIndex(jsonObjects);
                }else if("110001".equals(formTypeCode) && "1".equals(index)){
                    //标准级别：
                    List<BaseDict> bzjbList = DictUtil.getDictByType(DictTypes.BZJB);
                    for(BaseDict baseDict : bzjbList){
                        baseDict.setBadtLevel9("bzjb"+baseDict.getBadtCode());
                    }
                    dataMap.put("bzjbList",bzjbList);
                    addIndex(jsonObjects);
                }
                dataMap.put("records",jsonObjects);
                dataMap.put("yearmonth",DateUtil.getCurrentDateNoSpliter());
                String fileName  = getExportExcelName(formTypeCode,formInfo,index);
                File formExcel = createFormExcel(formTypeCode+index, fileName, dataMap);
                String tempFilePath = uploadUtil.getTempPath()+File.separator+ new Date().getTime()
                        +File.separator+fileName+formExcel.getName().substring(formExcel.getName().lastIndexOf("."));
                File tempFile = new File(tempFilePath);
                if(!tempFile.getParentFile().exists()){
                    tempFile.getParentFile().mkdirs();
                }
                tempFile.createNewFile();
                if("110007".equals(formTypeCode) && "2".equals(index)){
                    //合并一些单元格：
                    mergeTable(formExcel,tempFile);
                }
                FileUtils.copyFile(formExcel,tempFile);
                formExcel.delete();
                SupervisorFileTemp temp = new SupervisorFileTemp();
                temp.setUrl(tempFile.getPath());
                temp.setFileName(tempFile.getName());
                temp.setFileType(tempFile.getName().substring(tempFile.getName().lastIndexOf(".")));
                temp.setType(formTypeCode+"tz");
                tempService.insertSelective(temp);
                result.setFlag(true);
                result.setData(temp.getId());
                return result;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        result.setFlag(false);
        return result;
    }

    /**
     * 导出表单相关统计表格数据
     * @return
     */
    @RequestMapping("/form/export/statistics/{formTypeCode}")
    public void exportStatisticsExcel(@PathVariable String formTypeCode, SupervisorProjectFromsDTO formInfo, HttpServletRequest request, HttpServletResponse response,String index){
        ReType reType = new ReType();
        if(StringUtils.isBlank(formTypeCode)){
            log.warning("导出表单类统计表格时,没有获取到表单类型编码");
            return ;
        }
        ReType reType1 = selectFormScientific(formTypeCode, formInfo, "1", Integer.MAX_VALUE + "",index);
        List<?> data1 = reType1.getData();
        if(CollectionUtil.isNotEmpty(data1)){
            try{
                List<Map> data = (List<Map>)reType1.getData();
                for (int i = 0; i <data.size() ; i++) {
                    Map map = data.get(i);
                    map.put("fileInd",i+1);
                }
                String s = JSONArray.toJSONString(data);
                List<JSONObject> jsonObjects = JSONArray.parseArray(s, JSONObject.class);
                HashMap dataMap = new HashMap();
                if("110007".equals(formTypeCode)){
                    if("0".equals(index) || "1".equals(index)){
                        List<String> kyxmYears0 = itFormMapper.getKyxmYears0(formInfo);
                        dataMap.put("years",kyxmYears0);
                    }
                    if("3".equals(index)){
                        //项目级别列表
                        List<BaseDict> xmjbDictList = DictUtil.getDictByType(DictTypes.XMJB);
                        dataMap.put("xmjbDictList",xmjbDictList);
                        addIndex(jsonObjects);
                    }
                }else if("110005".equals(formTypeCode)){
                    List<String> authorIndexListTj = lunWenFormService.getAuthorIndexListTj(formInfo);
                    if(CollectionUtil.isNotEmpty(authorIndexListTj)){
                        List<String> newResult = new ArrayList<String>();
                        for(int i=0;i<authorIndexListTj.size();i++){
                            newResult.add(authorIndexListTj.get(i));
                            if(i > 4){
                                break;
                            }
                        }
                        dataMap.put("authorIndexList",newResult);
                    }
                    List<BaseDict> dictByType = DictUtil.getDictByType(DictTypes.QKLX);
                    dataMap.put("qklxList",dictByType);
                    addIndex(jsonObjects);
                }else if("110002".equals(formTypeCode)){
                    addIndex(jsonObjects);
                    //填充专利类型:
                    List<BaseDict> zllxList = DictUtil.getDictByType(DictTypes.ZLLX);
                    dataMap.put("zllxList",zllxList);
                    if("0".equals(index)){
                        List<String> famingrenIndexListTj = zhuanliFormService.getFamingrenIndexListTj(formInfo);
                        if(CollectionUtil.isNotEmpty(famingrenIndexListTj)){
                            List<String> tableFaMingRenIndexList = new ArrayList<>();
                            for(int i=0;i<famingrenIndexListTj.size();i++){
                                tableFaMingRenIndexList.add(famingrenIndexListTj.get(i));
                                if(i > 6){
                                    break;
                                }
                            }
                            dataMap.put("famingrenIndexList",tableFaMingRenIndexList);
                        }
                    }
                }else if("110003".equals(formTypeCode)){
                    addIndex(jsonObjects);
                }else if("110006".equals(formTypeCode)){
                    addIndex(jsonObjects);
                }else if("110001".equals(formTypeCode) && "1".equals(index)){
                    //标准级别：
                    List<BaseDict> bzjbList = DictUtil.getDictByType(DictTypes.BZJB);
                    for(BaseDict baseDict : bzjbList){
                        baseDict.setBadtLevel9("bzjb"+baseDict.getBadtCode());
                    }
                    dataMap.put("bzjbList",bzjbList);
                    addIndex(jsonObjects);
                }
                dataMap.put("records",jsonObjects);
                dataMap.put("yearmonth",DateUtil.getCurrentDateNoSpliter());
                String fileName  = getExportExcelName(formTypeCode,formInfo,index);
                if("110007".equals(formTypeCode) && "2".equals(index)){
                    exportExcel(response,dataMap,fileName,formTypeCode+index);
                }
                ExcelExportUtil.exportExcel(response,dataMap,fileName,formTypeCode+index);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 科研项目统计,导出时需要合并单元格,使用此方法
     * @param response
     * @param dataMap
     * @param fileName
     * @param fp_id
     * @throws IOException
     */
    public void exportExcel(HttpServletResponse response,HashMap dataMap,String fileName,String  fp_id)  throws IOException {
        try {
            // 获取模板信息
            String srcFilePath = FilePathUtil.getPathConfigTemplateFile(fp_id);
            response.reset();
            response.setContentType("application" + File.separator + "vnd.ms-excel");   //下载文版类型
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
            //生成的临时导出文件
            File destFile = File.createTempFile("123456", ".xls");
            //  开始转换。利用  transformer 转到Excel
            XLSTransformer transformer = new XLSTransformer();
            // 参数：srcFilePath：模板源文件    cMap：需要导出的数据   destFile.getAbsolutePath()：下载的目标文件
            transformer.transformXLS(srcFilePath, dataMap, destFile.getAbsolutePath());

            File targetFile = File.createTempFile(fileName,".xls");
            mergeTable(destFile,targetFile);
            FileInputStream fis = new FileInputStream(targetFile);
            OutputStream out = response.getOutputStream();
            byte[] bytes = new byte[512];
            int i = 0;
            while ((i = fis.read(bytes)) != -1) {
                out.write(bytes, 0, i);
            }
            out.close();
            fis.close();
            destFile.delete();
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }

    }


    /**
     * 创建表单临时表格文件
     * @param formTypeCode
     * @param fileName
     * @param dataMap
     * @return
     */
    public File createFormExcel(String formTypeCode,String fileName,HashMap dataMap){
        try {
            // 获取模板信息
            String srcFilePath = FilePathUtil.getPathConfigTemplateFile(formTypeCode);
            //生成的临时导出文件
            File destFile  = File.createTempFile(fileName, ".xls");
            //  开始转换。利用  transformer 转到Excel
            XLSTransformer transformer = new XLSTransformer();
            // 参数：srcFilePath：模板源文件    cMap：需要导出的数据   destFile.getAbsolutePath()：下载的目标文件
            transformer.transformXLS(srcFilePath, dataMap, destFile.getAbsolutePath());
            return destFile;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 处理对象中的一些字典数据,集合数据
     * 转换为表格中使用的数据
     * @param dataList
     */
    private List<?> handlerData(String formTypeCode,List<?> dataList) {
        if(CollectionUtil.isNotEmpty(dataList)){
            FormType formType = FormType.getFormType(formTypeCode);
            switch (formType){
                case ZZCBBZ:
                    return handlerZZCBBZ(dataList);
                case ZL:
                    return handlerZL(dataList);
                case RZ:
                    return handlerRZ(dataList);
                case JCDLBT:
                    return handlerRZ(dataList);
                case LW:
                    return handlerLW(dataList);
                case SZ:
                    return handlerSZ(dataList);
                case KYXMK:
                    return handlerKyxmxx(dataList);
            }
        }
        return null;
    }

    /**
     * 处理科研项目信息对象
     * @param dataList
     */
    private List<?> handlerKyxmxx(List<?> dataList) {
        List<SupervisorProjectFromsDTO> data = new ArrayList<SupervisorProjectFromsDTO>();
        if(CollectionUtil.isNotEmpty(dataList)){
            data = (ArrayList<SupervisorProjectFromsDTO>) dataList;
        }
        if(CollectionUtil.isNotEmpty(data)){
            for(SupervisorProjectFromsDTO formDto : data){
                //项目级别:
                if(StringUtils.isNotBlank(formDto.getSpfF2())){
                    BaseDict dictByCode = DictUtil.getDictByCode(DictTypes.XMJB, formDto.getSpfF2());
                    if(dictByCode != null && StringUtils.isNotBlank(dictByCode.getBadtName())){
                        formDto.setExcelStr1(dictByCode.getBadtName());
                    }else{
                        formDto.setExcelStr1("");
                    }
                }
                //计划类别:
                if(StringUtils.isNotBlank(formDto.getSpfF3())){
                    BaseDict dictByCode = DictUtil.getDictByCode(DictTypes.JHLB, formDto.getSpfF3());
                    if(dictByCode != null && StringUtils.isNotBlank(dictByCode.getBadtName())){
                        formDto.setExcelStr2(dictByCode.getBadtName());
                    }else{
                        formDto.setExcelStr2("");
                    }
                }
                //项目进度:
                if(StringUtils.isNotBlank(formDto.getSpfF11())){
                    BaseDict dictByCode = DictUtil.getDictByCode(DictTypes.XMJD, formDto.getSpfF11());
                    if(dictByCode != null && StringUtils.isNotBlank(dictByCode.getBadtName())){
                        formDto.setExcelStr3(dictByCode.getBadtName());
                    }else{
                        formDto.setExcelStr3("");
                    }
                }
                //申报项目团队成员
                ArrayList<SupervisorProjectFormsData> formDataList = formDto.getFormDataList();
                if(CollectionUtil.isNotEmpty(formDataList)){
                    StringBuffer mems = new StringBuffer();
                    for(SupervisorProjectFormsData formData : formDataList){
                        if(StringUtils.isNotBlank(formData.getData1())){
                            mems.append(formData.getData1());
                            mems.append("\n");
                        }
                    }
                    formDto.setExcelStr4(mems.toString());
                }else{
                    formDto.setExcelStr4("");
                }
                //项目实施团队成员
                ArrayList<SupervisorProjectFormsData> formDataList2 = formDto.getFormDataList2();
                if(CollectionUtil.isNotEmpty(formDataList2)){
                    StringBuffer mems = new StringBuffer();
                    for(SupervisorProjectFormsData formData : formDataList2){
                        if(StringUtils.isNotBlank(formData.getData1())){
                            mems.append(formData.getData1());
                            mems.append("\n");
                        }
                    }
                    formDto.setExcelStr5(mems.toString());
                }else{
                    formDto.setExcelStr5("");
                }
                //设置文件名称
                for(int i=0;i<9;i++){
                try {
                    Field declaredField = formDto.getClass().getDeclaredField("fileList" + (i+1));
                    declaredField.setAccessible(true);
                    Object o = declaredField.get(formDto);
                    if(o != null){
                        ArrayList<SupervisorFile> fileList = (ArrayList<SupervisorFile>) o;
                        Field fileNameField = formDto.getClass().getDeclaredField("fileNames" + (i+1));
                        fileNameField.setAccessible(true);
                        if(CollectionUtil.isNotEmpty(fileList)){
                            StringBuffer fileNames = new StringBuffer();
                            for(SupervisorFile aFile : fileList){
                                if(StringUtils.isNotBlank(aFile.getFileName())){
                                    fileNames.append(aFile.getFileName());
                                    fileNames.append("\n");
                                }
                            }
                            fileNameField.set(formDto,fileNames.toString());
                        }else{
                            fileNameField.set(formDto,"");
                        }
                    }
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            }
        }
        return data;
    }

    /**
     * 处理专利信息对象
     * @param dataList
     */
    private List<?> handlerZL(List<?> dataList) {
        List<SupervisorProjectFromsDTO> data = new ArrayList<SupervisorProjectFromsDTO>();
        if(CollectionUtil.isNotEmpty(dataList)){
            data = (ArrayList<SupervisorProjectFromsDTO>) dataList;
        }
        if(CollectionUtil.isNotEmpty(data)){
            for(SupervisorProjectFromsDTO formDto : data){
                //专利类型:
                if(StringUtils.isNotBlank(formDto.getSpfF2())){
                    BaseDict dictByCode = DictUtil.getDictByCode(DictTypes.ZLLX, formDto.getSpfF2());
                    if(dictByCode != null && StringUtils.isNotBlank(dictByCode.getBadtName())){
                        formDto.setExcelStr1(dictByCode.getBadtName());
                    }else{
                        formDto.setExcelStr1("");
                    }
                }
                //阶段:
                if(StringUtils.isNotBlank(formDto.getSpfF3())){
                    BaseDict dictByCode = DictUtil.getDictByCode(DictTypes.ITJD, formDto.getSpfF3());
                    if(dictByCode != null && StringUtils.isNotBlank(dictByCode.getBadtName())){
                        formDto.setExcelStr2(dictByCode.getBadtName());
                    }else{
                        formDto.setExcelStr2("");
                    }
                }
                //发明人:
                Object obj1 = formDto.getObj1();
                if(null != obj1){
                    ArrayList<SupervisorProjectFormsData> famingrenList = (ArrayList<SupervisorProjectFormsData>) obj1;
                    String excelStr3 = "";
                    if(CollectionUtil.isNotEmpty(famingrenList)){
                        for(int i=0;i<famingrenList.size();i++){
                            SupervisorProjectFormsData aFaMingRen = famingrenList.get(i);
                            if(i == famingrenList.size()-1){
                                excelStr3 += aFaMingRen.getData1();
                            }else{
                                excelStr3 += aFaMingRen.getData1()+"\r\n";
                            }
                        }
                    }
                    formDto.setExcelStr3(excelStr3);
                }
                //年费处理:
                Object obj2 = formDto.getObj2();
                if(null != obj2){
                    ArrayList<SupervisorProjectFormsData> nianfeiList = (ArrayList<SupervisorProjectFormsData>) obj2;
                    StringBuilder head = new StringBuilder();
                    int width = 30;
                    head.append(getALineData("序号",10))
                            .append(getALineData("金额",10))
                            .append(getALineData("缴费时间",20))
                            .append(getALineData("年费跨度",20))
                            .append(getALineData("经办人",14))
                            .append("\r\n");
                    if(CollectionUtil.isNotEmpty(nianfeiList)){

                        for(int i=0;i<nianfeiList.size();i++){
                            SupervisorProjectFormsData aNianFei = nianfeiList.get(i);
                            head.append(getALineData((Integer.valueOf(aNianFei.getTableIndex())+1)+"",10))
                                    .append(getALineData(aNianFei.getData2(),10))
                                    .append(getALineData(aNianFei.getData3(),20))
                                    .append(getALineData(aNianFei.getData4(),20))
                                    .append(getALineData(aNianFei.getData5(),14));
                            if(i != nianfeiList.size()-1){
                                head.append("\r\n");
                            }
                        }
                    }
                    formDto.setExcelStr4(head.toString());
                }
                //设置文件名称
                for(int i=0;i<9;i++){
                    try {
                        Field declaredField = formDto.getClass().getDeclaredField("fileList" + (i+1));
                        declaredField.setAccessible(true);
                        Object o = declaredField.get(formDto);
                        if(o != null){
                            ArrayList<SupervisorFile> fileList = (ArrayList<SupervisorFile>) o;
                            Field fileNameField = formDto.getClass().getDeclaredField("fileNames" + (i+1));
                            fileNameField.setAccessible(true);
                            if(CollectionUtil.isNotEmpty(fileList)){
                                StringBuffer fileNames = new StringBuffer();
                                for(int b=0;b<fileList.size();b++){
                                    SupervisorFile aFile = fileList.get(b);
                                    if(StringUtils.isNotBlank(aFile.getFileName())){
                                        fileNames.append(aFile.getFileName());
                                        if(b != fileList.size()-1){
                                            fileNames.append("\n");
                                        }
                                    }
                                }
                                fileNameField.set(formDto,fileNames.toString());
                            }else{
                                fileNameField.set(formDto,"");
                            }
                        }
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return data;
    }

    /**
     * 处理书著信息对象
     * @param dataList
     */
    private List<?> handlerSZ(List<?> dataList) {
        List<SupervisorProjectFromsDTO> data = new ArrayList<SupervisorProjectFromsDTO>();
        if(CollectionUtil.isNotEmpty(dataList)){
            data = (ArrayList<SupervisorProjectFromsDTO>) dataList;
        }


        List<JSONObject> result = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(data)){
            for(SupervisorProjectFromsDTO formDto : data){

                //设置文件名称
                for(int i=0;i<9;i++){
                    try {
                        Field declaredField = formDto.getClass().getDeclaredField("fileList" + (i+1));
                        declaredField.setAccessible(true);
                        Object o = declaredField.get(formDto);
                        if(o != null){
                            ArrayList<SupervisorFile> fileList = (ArrayList<SupervisorFile>) o;
                            Field fileNameField = formDto.getClass().getDeclaredField("fileNames" + (i+1));
                            fileNameField.setAccessible(true);
                            if(CollectionUtil.isNotEmpty(fileList)){
                                StringBuffer fileNames = new StringBuffer();
                                for(int b=0;b<fileList.size();b++){
                                    SupervisorFile aFile = fileList.get(b);
                                    if(StringUtils.isNotBlank(aFile.getFileName())){
                                        fileNames.append(aFile.getFileName());
                                        if(b != fileList.size()-1){
                                            fileNames.append("\n");
                                        }
                                    }
                                }
                                fileNameField.set(formDto,fileNames.toString());
                            }else{
                                fileNameField.set(formDto,"");
                            }
                        }
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }

                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(formDto), JSONObject.class);
                System.out.println(jsonObject);
                if(jsonObject.get("obj1") != null){
                    JSONArray zhuBianArray = (JSONArray) jsonObject.get("obj1");
                    if(CollectionUtil.isNotEmpty(zhuBianArray)){
                        for(int i=0;i<zhuBianArray.size();i++){
                            Object o = zhuBianArray.get(i);
                            JSONObject aZhuBianJson = (JSONObject) o;
                            jsonObject.put("zhuBian"+aZhuBianJson.get("tableIndex").toString(),aZhuBianJson.get("data1"));
                        }
                    }
                }
                if(jsonObject.get("obj2") != null){
                    JSONArray bianWeiArray = (JSONArray) jsonObject.get("obj2");
                    if(CollectionUtil.isNotEmpty(bianWeiArray)){
                        for(int i=0;i<bianWeiArray.size();i++){
                            Object o = bianWeiArray.get(i);
                            JSONObject aBianWeiJson = (JSONObject) o;
                            jsonObject.put("bianWei"+aBianWeiJson.get("tableIndex").toString(),aBianWeiJson.get("data1"));
                        }
                    }
                }
                result.add(jsonObject);
            }
        }
        return result;
    }

    /**
     * 处理正中参编标准信息对象
     * @param dataList
     */
    private List<?> handlerZZCBBZ(List<?> dataList) {
        List<SupervisorProjectFromsDTO> data = new ArrayList<SupervisorProjectFromsDTO>();
        if(CollectionUtil.isNotEmpty(dataList)){
            data = (ArrayList<SupervisorProjectFromsDTO>) dataList;
        }


        List<JSONObject> result = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(data)){
            for(SupervisorProjectFromsDTO formDto : data){
                //标准状态:
                if(StringUtils.isNotBlank(formDto.getSpfF2())){
                    BaseDict dictByCode = DictUtil.getDictByCode(DictTypes.STATE, formDto.getSpfF2());
                    if(dictByCode != null && StringUtils.isNotBlank(dictByCode.getBadtName())){
                        formDto.setExcelStr1(dictByCode.getBadtName());
                    }else{
                        formDto.setExcelStr1("");
                    }
                }
                //标准级别:
                if(StringUtils.isNotBlank(formDto.getSpfF3())){
                    BaseDict dictByCode = DictUtil.getDictByCode(DictTypes.BZJB, formDto.getSpfF3());
                    if(dictByCode != null && StringUtils.isNotBlank(dictByCode.getBadtName())){
                        formDto.setExcelStr2(dictByCode.getBadtName());
                    }else{
                        formDto.setExcelStr2("");
                    }
                }
                //正中角色:
                if(StringUtils.isNotBlank(formDto.getSpfF6())){
                    BaseDict dictByCode = DictUtil.getDictByCode(DictTypes.ZZJS, formDto.getSpfF6());
                    if(dictByCode != null && StringUtils.isNotBlank(dictByCode.getBadtName())){
                        formDto.setExcelStr3(dictByCode.getBadtName());
                    }else{
                        formDto.setExcelStr3("");
                    }
                }
                //设置文件名称
                for(int i=0;i<2;i++){
                    try {
                        Field declaredField = formDto.getClass().getDeclaredField("fileList" + (i+1));
                        declaredField.setAccessible(true);
                        Object o = declaredField.get(formDto);
                        if(o != null){
                            ArrayList<SupervisorFile> fileList = (ArrayList<SupervisorFile>) o;
                            Field fileNameField = formDto.getClass().getDeclaredField("fileNames" + (i+1));
                            fileNameField.setAccessible(true);
                            if(CollectionUtil.isNotEmpty(fileList)){
                                StringBuffer fileNames = new StringBuffer();
                                for(int b=0;b<fileList.size();b++){
                                    SupervisorFile aFile = fileList.get(b);
                                    if(StringUtils.isNotBlank(aFile.getFileName())){
                                        fileNames.append(aFile.getFileName());
                                        if(b != fileList.size()-1){
                                            fileNames.append("\n");
                                        }
                                    }
                                }
                                fileNameField.set(formDto,fileNames.toString());
                            }else{
                                fileNameField.set(formDto,"");
                            }
                        }
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }

                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(formDto), JSONObject.class);
                System.out.println(jsonObject);
                if(jsonObject.get("obj1") != null){
                    JSONArray qiCaoRenArrayList = (JSONArray) jsonObject.get("obj1");
                    if(CollectionUtil.isNotEmpty(qiCaoRenArrayList)){
                        for(int i=0;i<qiCaoRenArrayList.size();i++){
                            Object o = qiCaoRenArrayList.get(i);
                            JSONObject qiCaoRenJson = (JSONObject) o;
                            jsonObject.put("qiCaoRenName"+qiCaoRenJson.get("tableIndex").toString(),qiCaoRenJson.get("data1"));
                            jsonObject.put("qiCaoRenOrder"+qiCaoRenJson.get("tableIndex").toString(),qiCaoRenJson.get("data2"));
                        }
                    }
                }
                result.add(jsonObject);
            }
        }
        return result;
    }


    /**
     * 处理科研项目信息对象
     * @param dataList
     */
    private List<?> handlerRZ(List<?> dataList) {
        List<SupervisorProjectFromsDTO> data = new ArrayList<SupervisorProjectFromsDTO>();
        if(CollectionUtil.isNotEmpty(dataList)){
            data = (ArrayList<SupervisorProjectFromsDTO>) dataList;
        }
        if(CollectionUtil.isNotEmpty(data)){
            for(SupervisorProjectFromsDTO formDto : data){
                //设置文件名称
                for(int i=0;i<9;i++){
                    try {
                        Field declaredField = formDto.getClass().getDeclaredField("fileList" + (i+1));
                        declaredField.setAccessible(true);
                        Object o = declaredField.get(formDto);
                        if(o != null){
                            ArrayList<SupervisorFile> fileList = (ArrayList<SupervisorFile>) o;
                            Field fileNameField = formDto.getClass().getDeclaredField("fileNames" + (i+1));
                            fileNameField.setAccessible(true);
                            if(CollectionUtil.isNotEmpty(fileList)){
                                StringBuffer fileNames = new StringBuffer();
                                for(int b=0;b<fileList.size();b++){
                                    SupervisorFile aFile = fileList.get(b);
                                    if(StringUtils.isNotBlank(aFile.getFileName())){
                                        fileNames.append(aFile.getFileName());
                                        if(b != fileList.size()-1){
                                            fileNames.append("\n");
                                        }
                                    }
                                }
                                fileNameField.set(formDto,fileNames.toString());
                            }else{
                                fileNameField.set(formDto,"");
                            }
                        }
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return data;
    }


    private String getALineData(String data,int width){
        if(data == null){
            data = "";
        }
        if(StringUtil.getRealLength(data) > width){
            return data;
        }else{
            int spaceCount = (width - StringUtil.getRealLength(data))/2;
            StringBuilder result = new StringBuilder();
            for(int i=0;i<spaceCount;i++){
                result.append(" ");
            }
            result.append(data);
            for(int i=0;i<spaceCount;i++){
                result.append(" ");
            }
            String resultStr = result.toString();
            if(StringUtil.getRealLength(resultStr) < width){
                int diff = width - StringUtil.getRealLength(resultStr);
                for(int a=0;a<diff;a++){
                    result.append(" ");
                }
            }
            return result.toString();
        }
    }


    private List<?> handlerLW(List<?> dataList){
        ArrayList<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
        if(CollectionUtil.isNotEmpty(dataList)){
            data = (ArrayList<Map<String,Object>>) dataList;
        }
        if(CollectionUtil.isNotEmpty(data)){
            for(Map aMap : data){
                //期刊类型:
                if(aMap.get("spfF3") != null && StringUtils.isNotBlank((String)aMap.get("spfF3"))){
                    BaseDict dictByCode = DictUtil.getDictByCode(DictTypes.QKLX, (String)aMap.get("spfF3"));
                    if(dictByCode != null && StringUtils.isNotBlank(dictByCode.getBadtName())){
                        aMap.put("excelStr1",dictByCode.getBadtName());
                    }else{
                        aMap.put("excelStr1","");
                    }
                }
                //期刊分类:
                if(aMap.get("spfF6") != null && StringUtils.isNotBlank((String)aMap.get("spfF6"))){
                    BaseDict dictByCode = DictUtil.getDictByCode(DictTypes.QKFL, (String)aMap.get("spfF6"));
                    if(dictByCode != null && StringUtils.isNotBlank(dictByCode.getBadtName())){
                        aMap.put("excelStr2",dictByCode.getBadtName());
                    }else{
                        aMap.put("excelStr2","");
                    }
                }

                //设置文件名称
                for(int i=0;i<9;i++){
                        Object o = aMap.get("fileList"+(i+1));
                        if(o != null){
                            ArrayList<SupervisorFile> fileList = (ArrayList<SupervisorFile>) o;
                            if(CollectionUtil.isNotEmpty(fileList)){
                                StringBuffer fileNames = new StringBuffer();
                                for(SupervisorFile aFile : fileList){
                                    if(StringUtils.isNotBlank(aFile.getFileName())){
                                        fileNames.append(aFile.getFileName());
                                        fileNames.append("\n");
                                    }
                                }
                                aMap.put("fileNames"+(i+1),fileNames.toString());
                            }else{
                                aMap.put("fileNames"+(i+1),"");
                            }
                        }
                }
            }
        }
        return data;
    }

    /**
     * 获取导出的台账文件名称
     * @param formTypeCode
     * @return
     */
    private String getExportExcelName(String formTypeCode) {
        return itFormAboutService.getExportExcelName(formTypeCode);
    }

    private String getExportExcelName(String formTypeCode,SupervisorProjectFromsDTO formDto,String index){
        return formBaseService.getExportExcelName(formTypeCode,formDto,index);
    }

}
